﻿using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using PoemGame.Domain.PlayerAggregate;

namespace PoemGame.Repository.EF
{
    /// <summary>
    /// 玩家存储库， 需要与Unit of Work一起工作
    /// 需要调用工作单元的SaveChanges进行实际保存
    /// </summary>
    public class PlayerRepositoryUoW:IPlayerRepository
    {
        private readonly PoemGameDbContext dbContext;
        public PlayerRepositoryUoW(PoemGameDbContext dbContext)
        {
            this.dbContext = dbContext;
        }
        /// <summary>
        /// 根据用户名获取玩家
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public async Task<Player?> GetPlayerByUserNameAsync(string username)
        {
            var player = await dbContext.Players.FirstOrDefaultAsync(o=>o.UserName==username);
            return player;
        }
        /// <summary>
        /// 根据标识获取玩家
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Player?> GetPlayerByIdAsync(Guid id)
        {
            var player= await dbContext.Players.FindAsync(id);
            return player;
        }
        /// <summary>
        /// 添加玩家
        /// </summary>
        /// <param name="player"></param>
        /// <returns></returns>
        public async Task<Guid> AddAsync(Player player)
        {
            await dbContext.Players.AddAsync(player);
            return player.Id;
        }
        /// <summary>
        /// 移除玩家
        /// </summary>
        /// <param name="player"></param>
        /// <returns></returns>
        public async Task RemoveAsync(Player player)
        {
            dbContext.Players.Remove(player);
        }
        /// <summary>
        /// 更新玩家
        /// </summary>
        /// <param name="player"></param>
        /// <returns></returns>
        public async Task UpdateAsync(Player player)
        {
            dbContext.Players.Update(player);
        }
        /// <summary>
        /// 获取所有玩家
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<Player>> GetAllAsync()
        {
            return await dbContext.Players.ToListAsync();
        }
        /// <summary>
        /// 获取符合条件的玩家
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public async Task<IEnumerable<Player>> GetByConditionAsync(Expression<Func<Player, bool>> predicate)
        {
            return await dbContext.Players.Where(predicate).ToListAsync();
        }
    }
}
